<template>
  <div id="get_code">
    <!-- title part -->
    <div class="title">
      <div class="title_font">获取验证码</div>
      <div class="title_discripe">已发送验证码至 {{ phone }}</div>
    </div>

    <!-- codeInput part -->
    <div class="codePart">
      <!-- <div class="six-input-box">
        <input
          v-for="(item, index) in inputbox"
          :key="index"
          :ref="`ref${index}`"
          class="codeInput"
          v-model.trim="item.value"
          type="tel"
          oninput="value=value.replace(/[^\d]/g,'')"
          @input="onInput(index)"
          @keyup.delete="onDelete(index)"
          @paste="onPaste"
          maxlength="1"
        />
      </div> -->
      <SixInput :initFlag="initFlag" @complete="complete" @resetInitFlag="resetInitFlag" />
    </div>

    <!-- reSendTip part -->
    <div class="reSendTip">
      <div v-if="codeTimeingNum === 60">
        <span>未收到验证码？可以</span>
        <span class="reSend" @click.stop="reSendCode">重新发送</span>
      </div>
      <div v-else>
        <span>{{ codeTimeingNum }}S后可重新发送</span>
      </div>
    </div>

    <!-- bottom part -->
    <div class="bottomPart" v-show="hideshow">
      Copyright © 2022 海南原上区块链科技有限公司
      <br />
      <span @click="linkTo">All Rights Reserved</span>
    </div>
  </div>
</template>

<script>
import SixInput from "../../components/SixInput.vue";
import { mapActions, mapMutations } from "vuex";
import { userLoginApi, sendVerificationCodeApi } from "@/api";
import { iscode, reHeight, isWeixin } from "@/utils";
import { setCookie } from "@/utils/cookie.js";
import baseUrl from "@/utils/baseUrl.js";
export default {
  name: "GetCode",
  components: { SixInput },
  data() {
    return {
      // 手机号码
      phone: this.$route.query.phone,
      // 验证码
      code: "",
      // 验证码（六格输入框）
      inputbox: [
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        }
      ],
      six_box: ["", "", "", "", "", ""],
      // 存放粘贴进来的数字
      pasteResult: [],
      // 验证码计时数
      codeTimeingNum: 60,
      // 解决手机键盘弹起布局错位问题
      docmHeight: document.documentElement.clientHeight || document.body.clientHeight,
      showHeight: document.documentElement.clientHeight || document.body.clientHeight,
      hideshow: true, //显示或者隐藏footer
      // 邀请码
      inviteCode: null,
      // 一元购
      onebuy_code: null,
      // 参数里的商品id
      payload_id: this.$route.query.id ?? null,
      // 是否重置sixinput
      initFlag: false,
      enterFlag: true
    };
  },
  watch: {
    // 解决手机键盘弹起布局错位问题
    showHeight: function() {
      if (this.docmHeight > this.showHeight) {
        //隐藏
        this.hideshow = false;
      } else {
        //显示
        this.hideshow = true;
      }
    },
    // 监视6格是否都输满了
    // inputbox: {
    //   deep: true,
    //   handler(val) {
    //     let flag = true;
    //     val.forEach((item) => {
    //       if (item.value === "") {
    //         flag = false;
    //       }
    //     });
    //     if (flag) {
    //       this.inputbox.forEach((item) => {
    //         this.code += item.value;
    //       });
    //       this.userLogin();
    //     }
    //   },
    // },
    // 监视粘贴
    pasteResult(val) {
      if (val) {
        this.inputbox.forEach((item, index) => {
          item.value = this.pasteResult[index];
        });
      }
    }
  },
  mounted() {
    //监听事件
    window.onresize = () => {
      return (() => {
        this.showHeight = document.documentElement.clientHeight || document.body.clientHeight;
      })();
    };

    // 一进入就获取焦点
    // this.$nextTick(() => {
    //   this.$refs.ref0[0].focus();
    // });
    reHeight("get_code", this);

    // if (this.$route.query.inviteCode) {
    //   this.inviteCode = "I-" + this.$route.query.inviteCode;
    // }
    // if (this.$route.query.onebuy_code) {
    //   this.onebuy_code = "O-" + this.$route.query.onebuy_code;
    // }
  },
  methods: {
    // ----- store -----
    // 获取用户信息（用于认证之后更新vuex里的userInfo数据）
    ...mapActions(["getUserInfo"]),
    ...mapMutations(["clearUserInfo"]),

    // ------ 异步相关 ------
    // 登录（登录成功则跳转到个人中心）
    async userLogin() {
      let res = await userLoginApi({
        phone: this.phone,
        verify_code: this.code,
        invite_code: this.$route.query.inviteCode ?? "",
        onebuy_code: this.$route.query.onebuy_code ?? "",
        secret: this.$route.query.secret
      });
      if (iscode(res)) {
        window.localStorage.setItem("isLogin", true);
        window.localStorage.setItem("phoneFirstLogin", true);
        setCookie("token", res.result.token, 7);
        window.localStorage.setItem("token", JSON.stringify(res.result.token));
        this.$toast({ message: "登录成功", type: "success" });
        if (isWeixin()) {
          location.assign(
            `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx55eb0c5e4cf93b2d&redirect_uri=${
              baseUrl.productionWeb
            }&response_type=code&scope=snsapi_base&state=${-1}+${this.payload_id ??
              -1}#wechat_redirect`
          );
          return;
        }
        // 如果商品id参数存在，则跳转到对应页面
        if (this.$route.query.id) {
          this.$router.push({
            path: "/mail/productDetail",
            query: {
              id: this.$route.query.id - 0
            }
          });
        } else {
          this.$router.push("/");
        }
        this.getUserInfo();
        this.code = "";
        this.initFlag = true;
      } else {
        this.code = "";
        this.initFlag = true;
      }
    },
    // 发送短信验证码
    async reSendCode() {
      this.inputbox.forEach((item) => {
        item.value = "";
      });
      this.code = "";

      let res = await sendVerificationCodeApi({
        phone: this.phone
      });
      if (iscode(res)) {
        this.$toast(res.message);

        if (res.code === 200005) {
          return;
        }

        // 验证码计时
        let codeTimer = setInterval(() => {
          this.codeTimeingNum = this.codeTimeingNum - 1;
          if (this.codeTimeingNum === 0) {
            clearInterval(codeTimer);
            this.codeTimeingNum = 60;
          }
        }, 1000);
      }
    },

    // ------ 功能相关 ------
    complete(valArr) {
      valArr.forEach((item) => {
        this.code += item;
      });

      if (this.enterFlag) {
        this.enterFlag = false;
        this.userLogin();
        setTimeout(() => {
          this.enterFlag = true;
        }, 1000);
      }
    },
    // 重置sixinput的initFlag（initFlag：用来判断是否初始化sixinput）
    resetInitFlag() {
      this.initFlag = false;
    },
    // 六格输入框输入事件
    onInput(index) {
      // index < 5 ，如果是第6格，不触发光标移动至下一个输入框。
      if (this.inputbox[index].value && index < 5) {
        this.$refs["ref" + (index + 1)][0].focus();
      }
      // var inputValue = "";
      // this.inputbox.forEach((item) => {
      //   inputValue = inputValue + item.value;
      // });
    },
    // 六格输入框删除事件
    onDelete(index) {
      // 如果是第1格，不触发光标移动至上一个输入框
      if (index > 0) {
        this.$refs["ref" + (index - 1)][0].focus();
      }
    },
    // 六格输入框当粘贴事件
    onPaste(e) {
      e.clipboardData.items[0].getAsString((str) => {
        if (str.toString().length === 6) {
          this.pasteResult = str.split("");
          document.activeElement.blur();
        }
      });
    },

    // ------ 跳转相关 ------
    // bottom part
    linkTo() {
      window.open("https://beian.miit.gov.cn/#/Integrated/index", "_blank");
    }
  }
};
</script>

<style lang="less" scoped>
#get_code {
  width: 100%;
  height: 100%;
  overflow: hidden;
  padding: 0 50px;

  // >> title区域
  .title {
    display: flex;
    flex-direction: column;
    margin-top: 224px;

    .title_font {
      font-size: 48px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #ffffff;
    }

    .title_discripe {
      font-size: 26px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      margin-top: 40px;
    }
  }

  // >> 验证码区域
  .codePart {
    display: flex;
    width: 100%;
    margin-top: 120px;

    .six-input-box {
      display: flex;
      flex-direction: row;
    }
    .codeInput {
      display: flex;
      width: 100px;
      height: 116px;
      font-size: 18px;
      color: #333333;
      background-color: #3f4141;
      text-align: center;
      outline: none;
      border: 0;
      font-size: 48px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #ffffff;
      margin-left: 10px;
    }
    .codeInput:nth-child(1) {
      margin-left: 0;
    }
  }

  // >> 重新发送验证码提示
  .reSendTip {
    width: 100%;
    margin-top: 40px;

    span {
      font-size: 24px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
    }
    .reSend {
      color: #00ffb0;
      margin-left: 12px;
    }
  }

  // >> 底部文字
  .bottomPart {
    position: absolute;
    left: 0;
    bottom: 64px;
    width: 100%;
    text-align: center;
    font-size: 24px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ffffff;
  }
}
</style>
